package com.crrcdt.vue_project.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crrcdt.vue_project.entity.*;
import com.crrcdt.vue_project.entity.vo.AttrVo;
import com.crrcdt.vue_project.entity.vo.Attrs;
import com.crrcdt.vue_project.result.Result;
import com.crrcdt.vue_project.result.ResultFactory;
import com.crrcdt.vue_project.service.AttributeService;
import com.crrcdt.vue_project.service.GoodsAttrService;
import com.crrcdt.vue_project.service.GoodsPicsService;
import com.crrcdt.vue_project.service.GoodsService;
import com.crrcdt.vue_project.util.OSSClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lj on 2020/10/24.
 * @version 1.0
 */
@RestController
@RequestMapping(value = "/api/private/v1")
@Slf4j
public class GoodController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    OSSClientUtil ossClient;
    @Autowired
    private GoodsAttrService goodsAttrService;
    @Autowired
    private GoodsPicsService goodsPicsService;
    @Autowired
    private AttributeService attributeService;
    @GetMapping("/goods")
    public Result getAllGoods(@RequestParam(name = "query", required = false) String query,
                              @RequestParam("pagenum") Long pagenum,
                              @RequestParam("pagesize") Long pagesize) {
        Page<Goods> page = new Page<>(pagenum, pagesize);
        final IPage<Goods> goodsIPage;
        if (StringUtils.isBlank(query)) {
            goodsIPage = goodsService.page(page, null);
        } else {
            goodsIPage = goodsService.page(page, new QueryWrapper<Goods>().like("goods_name", query));
        }
        HashMap<Object, Object> data = new HashMap<>();
        data.put("total", goodsIPage.getTotal());
        data.put("pagenum", goodsIPage.getCurrent());
        data.put("goods", goodsIPage.getRecords());
        return ResultFactory.buildSuccessResult(data, "获取成功");
    }

    //    添加商品
    @Transactional
    @PostMapping("/goods")
    public Result addGoods(@RequestBody Goods goods) {
        final String[] catIds = goods.getGoodsCat().split(",");
        goods.setAddTime((int) System.currentTimeMillis());
        goods.setCatId(Integer.parseInt(catIds[catIds.length - 1]));
        goods.setCatOneId(Integer.parseInt(catIds[0]));
        goods.setCatTwoId(Integer.parseInt(catIds[1]));
        goods.setCatThreeId(catIds.length == 3 ? Integer.parseInt(catIds[2]) : null);
        final boolean res = goodsService.save(goods);
        if (res) {
            // TODO 图片上传后期再处理细节
            final List<GoodsPics> goodsPicsList = goods.getPics().stream().map(entity -> {
                final GoodsPics goodsPics = new GoodsPics();
                goodsPics.setGoodsId(goods.getGoodsId());
                goodsPics.setPicsSma(entity.getPic());
                goodsPics.setPicsMid(entity.getPic());
                goodsPics.setPicsBig(entity.getPic());
                return goodsPics;
            }).collect(Collectors.toList());
            // 批量保存goodsPicsList
            final boolean imgRes = goodsPicsService.saveBatch(goodsPicsList);
            if (!imgRes) {
                return ResultFactory.buildFailResult("创建商品失败！");
            }
            //处理goodsAttrs
            final List<Attrs> attrs = goods.getAttrs();
            final List<GoodsAttr> goodsAttrs = attrs.stream().map(entity -> {
                entity.setGoodsId(goods.getGoodsId());
                final GoodsAttr goodsAttr = new GoodsAttr();
                BeanUtils.copyProperties(entity, goodsAttr);
                return goodsAttr;
            }).collect(Collectors.toList());
            // 批量保存goodsAttrs
            final boolean saveBatchRes = goodsAttrService.saveBatch(goodsAttrs);
            if (saveBatchRes) {
                return ResultFactory.buildSuccessResult(goods, "创建商品成功");
            }
        }
        return ResultFactory.buildFailResult("创建商品失败！");
    }

    // 阿里云oos上传图片
    @PostMapping("/upload")
    public Result uploadPic(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null || file.getSize() <= 0) {
            throw new Exception("图片不能为空");
        }
        String name = ossClient.uploadImg2Oss(file);
        String imgUrl = ossClient.getImgUrl(name);
        final HashMap<Object, Object> data = new HashMap<>();
        data.put("name", name);
        data.put("url", imgUrl);
        return ResultFactory.buildSuccessResult(data, "上传图片成功");
    }
    //    根据 ID 查询商品
    @GetMapping("/goods/{id}")
    public Result getGoodById(@PathVariable("id") int id) {
        // 得到good
        final Goods goods = goodsService.getById(id);
        // 得到attrs
        final List<GoodsAttr> goodsAttrs = goodsAttrService.list(new QueryWrapper<GoodsAttr>().eq("goods_id", goods.getGoodsId()));
        if(CollectionUtil.isNotEmpty(goodsAttrs)){
            final List<Attrs> attrsList = goodsAttrs.stream().map(entity -> {
                final Attrs attrs = new Attrs();
                BeanUtils.copyProperties(entity, attrs);
                // 根据分类id去找分类信息
                final Attribute attribute = attributeService.getById(entity.getAttrId());
                if(attribute!=null){
                    attrs.setAttrName(attribute.getAttrName());
                    attrs.setAttrSel(attribute.getAttrSel());
                    attrs.setAttrWrite(attribute.getAttrWrite());
                    attrs.setAttrValue(attribute.getAttrVals());
                    return attrs;
                }else{
                    return attrs;
                }
            }).collect(Collectors.toList());
            goods.setAttrs(attrsList);
            //得到图片pics 通过goodsid
            final List<GoodsPics> goodsPics = goodsPicsService.list(new QueryWrapper<GoodsPics>().eq("goods_id", id));
            final List<Pic> pics = goodsPics.stream().map(entity -> {
                final Pic pic = new Pic();
                pic.setPic(entity.getPicsSma());
                return pic;
            }).collect(Collectors.toList());
            goods.setPics(pics);
            return ResultFactory.buildSuccessResult(goods, "获取成功");
        }
        return ResultFactory.buildFailResult("获取失败！");
    }
    // TODO 编辑提交商品
    @Transactional
    @PutMapping("/goods/{id}")
    public Result updateGoods(@PathVariable("id") Integer id,@RequestBody Goods goods) {
        final String[] catIds = goods.getGoodsCat().split(",");
        goods.setUpdTime(((int) System.currentTimeMillis()));
        goods.setCatId(Integer.parseInt(catIds[catIds.length - 1]));
        goods.setCatOneId(Integer.parseInt(catIds[0]));
        goods.setCatTwoId(Integer.parseInt(catIds[1]));
        goods.setCatThreeId(catIds.length == 3 ? Integer.parseInt(catIds[2]) : null);
        goods.setGoodsId(id);
        final boolean res = goodsService.updateById(goods);
        if (res) {
            // TODO 图片上传后期再处理细节
            final List<GoodsPics> goodsPicsList = goods.getPics().stream().map(entity -> {
                final GoodsPics goodsPics = new GoodsPics();
                goodsPics.setGoodsId(goods.getGoodsId());
                goodsPics.setPicsSma(entity.getPic());
                goodsPics.setPicsMid(entity.getPic());
                goodsPics.setPicsBig(entity.getPic());
                return goodsPics;
            }).collect(Collectors.toList());
            // 批量更新goodsPicsList 先删除，后添加
            final List<Integer> ids = goodsPicsService.list(new QueryWrapper<GoodsPics>().eq("goods_id", id)).stream()
                    .map(GoodsPics::getPicsId).collect(Collectors.toList());
            final boolean delRes = goodsPicsService.removeByIds(ids);
            if(delRes){
                final boolean saveRes = goodsPicsService.saveBatch(goodsPicsList);
                if(!saveRes){
                    return ResultFactory.buildFailResult("创建商品失败！");
                }
            }
            //处理goodsAttrs
            final List<Attrs> attrs = goods.getAttrs();
            final List<GoodsAttr> goodsAttrs = attrs.stream().map(entity -> {
                entity.setGoodsId(goods.getGoodsId());
                final GoodsAttr goodsAttr = new GoodsAttr();
                BeanUtils.copyProperties(entity, goodsAttr);
                return goodsAttr;
            }).collect(Collectors.toList());
            // 批量更新goodsAttrs 先删除后添加
            final List<Integer> idList = goodsAttrService.list(new QueryWrapper<GoodsAttr>().eq("goods_id", id)).stream()
                    .map(GoodsAttr::getId).collect(Collectors.toList());
            final boolean removeRes = goodsAttrService.removeByIds(idList);
            if(removeRes){
                final boolean saveBatchRes = goodsAttrService.saveBatch(goodsAttrs);
                if (saveBatchRes) {
                    return ResultFactory.buildSuccessResult(goods, "创建商品成功");
                }
            }

        }
        return ResultFactory.buildFailResult("创建商品失败！");
    }
    //  删除商品
    @Transactional
    @DeleteMapping("/goods/{id}")
    public Result getAttrs(@PathVariable("id") Integer id) {
        // 删除goods
        final boolean res = goodsService.remove(new QueryWrapper<Goods>().eq("goods_id", id));
        if (res) {
            // 删除GoodsAttr
            final boolean result = goodsAttrService.remove(new QueryWrapper<GoodsAttr>().eq("goods_id", id));
            if (result) {
                // 删除goodspic
                final boolean goodspicRes = goodsPicsService.remove(new QueryWrapper<GoodsPics>().eq("good_id", id));
                if(goodspicRes){
                    return ResultFactory.buildSuccessResult(null, "删除商品成功！");
                }

            }
        }
        return ResultFactory.buildFailResult("删除商品失败！");
    }
}
